require("babel-polyfill");
import Gun from "gun/gun";

class GunDb {
  constructor() {
    // TODO: Singleton to configure and inject GUN.
    this._gun = Gun(); // { localStorage: false, radisk: false })
  }

  async get(key) {
    if (!key) throw new Error("Invalid key");
    return new Promise((resolve, reject) => {
      this._gun
        .get(key, cb => {
          if (cb.err) {
            reject(new Error(cb.err));
            return;
          }
        })
        .on(
          cb => {
            // TODO: Include key in the output object?
            resolve(cb);
          },
          { change: true }
        );
    });
  }

  async put(key, value) {
    if (!key) throw new Error("Invalid key");
    if (!value) throw new Error("Invalid value");
    return new Promise((resolve, reject) => {
      this._gun
        .get(key, cb => {
          if (cb.err) {
            reject(new Error(cb.err));
            return;
          }
        })
        // FIXME: Gun is not triggering the callback.
        .put(value, cb => {
          if (cb.err) {
            reject(new Error(cb.err));
            return;
          }
        })
        .on((data, key) => {
          // FIXME: Parse `data` instead of using `get`?
          resolve(this.get(key));
        });
    });
  }
}

export default GunDb;
